﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Extensions;

namespace CodePlex.DBedarf.Sharepoint.ListManager
{
    /// <summary>
    /// Interaktionslogik für ListEventhandler.xaml
    /// </summary>
    public partial class ListEventReceiverPage : AvalonDock.DocumentContent
    {

        List<Microsoft.SharePoint.SPList> _lists;
        logJournalMessageDelegate log;

        /// <summary>
        /// Initializes a new instance of the <see cref="FieldPropertyPage"/> class.
        /// </summary>
        /// <param name="fields">The fields.</param>
        /// <param name="refreshFieldsMethod">The refresh fields method.</param>
        /// <param name="logMethod">The log method.</param>
        public ListEventReceiverPage(logJournalMessageDelegate logMethod)
        {
            InitializeComponent();
            log = logMethod;
        }

        /// <summary>
        /// Sets the fields to edit.
        /// </summary>
        /// <value>The fields.</value>
        public List<Microsoft.SharePoint.SPList> Lists
        {
            set
            {
                _lists = value;
                Action_GetCurrentListsData();
            }
        }


        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            Action_GetAvailableEventReceiverTypes();
        }


        private void HandleError(Exception ex)
        {
            WindowExtender.ShowError(ex);
        }


        private void Useraction_BrowseForAssembly(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.Title = "Select Assembly";
                ofd.Filter = "*.dll|*.dll|*.*|*.*";
                if (ofd.ShowDialog() == true)
                {

                    cboClasses.Items.Clear();
                    txtAssembly.Text = "";

                    System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFile(ofd.FileName);
                    txtAssembly.Text = asm.FullName;
                    foreach (System.Type t in asm.GetExportedTypes())
                    {
                        if (t.IsClass)
                            if
                            (
                                chkShowOnlySPItemEventReceiver.IsChecked == false ||
                                t.IsSubclassOf(typeof(Microsoft.SharePoint.SPItemEventReceiver))
                            )
                                cboClasses.Items.Add(t.FullName);
                    }
                    if (!asm.GlobalAssemblyCache)
                    {
                        WindowExtender.ShowInfo("You have to put your Assembly to the GAC before press Add!");
                        //TODO R3 Add to GAC
                    }

                    if (cboClasses.Items.Count > 0)
                    {
                        cboClasses.SelectedIndex = 0;
                        cboClasses.IsEnabled = true;
                        cmdAdd.IsEnabled = true;
                    }
                    else
                    {
                        cmdAdd.IsEnabled = false;
                    }
                }//endif Assembyl selected
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        private void Useraction_AddNewHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                string msg = "";
                string msgBad = "";
                foreach (Microsoft.SharePoint.SPList list in _lists)
                {
                    try
                    {
                        list.EventReceivers.Add(
                            (Microsoft.SharePoint.SPEventReceiverType)Enum.Parse(
                            typeof(Microsoft.SharePoint.SPEventReceiverType),
                            cboListEventType.Text),
                            txtAssembly.Text,
                            cboClasses.SelectedItem.ToString());
                        msg += list.Title + ", ";
                        log(false, "add event receiver \"{1}\" / \"{2}\" to list \"{0}\"", list.Title, cboListEventType.Text, cboClasses.SelectedItem.ToString());
                    }
                    catch (Exception iex)
                    {
                        msgBad += string.Format("{0} - {1}\n", list.Title, iex.Message);
                    }
                }//end foreach
                if (msg.Length > 0) msg = msg.Substring(0, msg.Length - 2);//remove last ", "
                //if(msgBad.Length>0) msgBad=msgBad.Substring(0,msg.Length-2);//remove last ", "

                if (string.IsNullOrEmpty(msgBad))
                    WindowExtender.ShowInfo("EventReceiver added to {0}.", msg);
                else
                    WindowExtender.ShowInfo("EventReceiver Added to {0}.\nSome errors occured while save:\n{1}", msg, msgBad);

                Action_GetCurrentListsData();

            }
            catch (Exception ex)
            {
                HandleError(ex);
                log(true, "add event receiver to list. Message: {0}", ex.Message);
            }
        }

        private void Useraction_RemoveSelectedHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                if (lvwCurrentEventHandler.SelectedItems.Count > 0)
                {
                    foreach (System.Windows.Controls.ListViewItem li in lvwCurrentEventHandler.SelectedItems)
                    {
                        Microsoft.SharePoint.SPEventReceiverDefinition rec = li.Content as Microsoft.SharePoint.SPEventReceiverDefinition;
                        if (rec != null)
                        {
                            if (WindowExtender.AskYesNo("Remove EventReceiver", "Are you sure you want to remove this handler?\n\nType:\t{0}\nClass:\t{2}\nAssembly:\t{1}", rec.Type, rec.Assembly, rec.Class))
                            {
                                rec.Delete();
                                log(false, "remove event receiver \"{1}\" / \"{2}\" from list \"{0}\"", rec.HostId, rec.Type, rec.Class);
                            }
                        }
                    }
                    Action_GetCurrentListsData();
                }//end if SelectedItems.Count>0
                else
                {
                    WindowExtender.ShowInfo("Please select a receiver to delete.");
                }//end if else SelectedItems.Count>0
            }
            catch (Exception ex)
            {
                HandleError(ex);
                log(true, "remove event receiver from list. Message: {0}", ex.Message);
            }

        }


        private void Action_GetAvailableEventReceiverTypes()
        {
            if (cboListEventType != null)
            {
                cboListEventType.Items.Clear();
                foreach (string eventType in Enum.GetNames(typeof(Microsoft.SharePoint.SPEventReceiverType)))
                {
                    if (((bool)chkShowOnlySPItemEventReceiver.IsChecked && eventType.Contains("Item")) || chkShowOnlySPItemEventReceiver.IsChecked == false)
                        cboListEventType.Items.Add(eventType);
                }
                if (cboListEventType.Items.Count > 0) cboListEventType.SelectedIndex = 0;
            }
        }

        private void Action_GetCurrentListsData()
        {
            try
            {
                lblSelectedLists.Content = null;
                if (_lists == null) return;
                lvwCurrentEventHandler.Items.Clear();
                string msg = "";
                foreach (Microsoft.SharePoint.SPList list in _lists)
                {
                    msg += list.Title + ", ";
                    foreach (Microsoft.SharePoint.SPEventReceiverDefinition rec in list.EventReceivers)
                    {
                        ListViewItem li = new ListViewItem();
                        li.Content = rec;
                        li.Tag = rec;
                        lvwCurrentEventHandler.Items.Add(li);
                    }
                }

                if (msg.Length > 0) msg = msg.Substring(0, msg.Length - 2);//remove last ", "
                lblSelectedLists.Content = msg;
                if (lvwCurrentEventHandler.Items.Count > 0)
                {
                    expCurrentHandler.IsExpanded = true;
                    expNewHandler.IsExpanded = false;
                }
                else
                {
                    expCurrentHandler.IsExpanded = false;
                    expNewHandler.IsExpanded = true;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_chkOnlySPListItemChanged(object sender, RoutedEventArgs e)
        {
            Action_GetAvailableEventReceiverTypes();
        }
    }
}
